import request from '@/utils/request'
import { mockListCar, mockGetCar, mockAddCar, mockUpdateCar, mockDeleteCar, mockBatchDeleteCar, mockExportCar } from '@/utils/service'

// 环境变量，确定是否使用模拟数据
// 改为false以便连接真实的Spring Boot后端
const USE_MOCK = false 

// 查询车辆列表
export function listCar(query) {
  if (USE_MOCK) {
    return mockListCar(query)
  }
  return request({
    url: '/api/cars/list',
    method: 'get',
    params: query
  })
}

// 查询车辆详细信息
export function getCar(id) {
  if (USE_MOCK) {
    return mockGetCar(id)
  }
  return request({
    url: `/api/cars/${id}`,
    method: 'get'
  })
}

// 新增车辆
export function addCar(data) {
  if (USE_MOCK) {
    return mockAddCar(data)
  }
  return request({
    url: '/api/cars/add',
    method: 'post',
    data: data
  })
}

// 修改车辆
export function updateCar(data) {
  if (USE_MOCK) {
    return mockUpdateCar(data)
  }
  return request({
    url: '/api/cars/update',
    method: 'post',
    data
  })
}

// 删除车辆
export function deleteCar(id) {
  if (USE_MOCK) {
    return mockDeleteCar(id)
  }
  return request({
    url: `/api/cars/delete/${id}`,
    method: 'get'
  })
}

// 批量删除车辆
export function batchDeleteCar(ids) {
  if (USE_MOCK) {
    return mockBatchDeleteCar(ids)
  }
  // 由于后端可能没有批量删除的API，这里可以拆分为多个单独删除请求
  const idArray = ids.split(',');
  const promises = idArray.map(id => deleteCar(id));
  
  return Promise.all(promises).then(() => {
    return {
      code: 200,
      message: 'success',
      data: null
    }
  });
}

// 导出车辆数据
export function exportCar(query) {
  if (USE_MOCK) {
    return mockExportCar(query)
  }
  return request({
    url: '/api/cars/export',
    method: 'get',
    params: query,
    responseType: 'blob'
  })
}

// 获取车辆图片列表
export function getCarPhotos(carId) {
  return request({
    url: `/api/cars/${carId}/photos`,
    method: 'get'
  })
}

// 上传车辆图片
export function uploadCarPhoto(carId, formData) {
  return request({
    url: `/api/cars/${carId}/photos`,
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 删除车辆图片
export function deleteCarPhoto(photoId) {
  return request({
    url: `/api/cars/photos/${photoId}`,
    method: 'delete'
  })
}

// 获取所有车辆
export function getAllCars() {
  return request({
    url: '/api/cars/list',
    method: 'get'
  })
}

// 获取热门车型
export function getPopularCars() {
  return request({
    url: '/api/cars/popular',
    method: 'get'
  })
}

// 根据ID获取车辆
export function getCarById(id) {
  return request({
    url: `/api/cars/${id}`,
    method: 'get'
  })
}

// 创建车辆
export function createCar(data) {
  return request({
    url: '/api/cars/add',
    method: 'post',
    data
  })
} 